package com.agrm.comment.service.impl;

import com.agrm.api.client.GoodClient;
import com.agrm.api.client.MemberClient;
import com.agrm.api.client.OrderClient;
import com.agrm.comment.mapper.CommentMapper;
import com.agrm.comment.service.CommentService;
import com.agrm.model.comment.dto.CommentQuery;
import com.agrm.model.comment.pojo.Comment;
import com.agrm.model.common.dtos.PageRequestDto;
import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.good.pojo.Good;
import com.agrm.model.member.pojo.Member;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CacheConfig(cacheNames = "comment")
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper,Comment> implements CommentService {


    @Autowired
    private GoodClient goodClient;
    @Autowired
    private OrderClient orderClient;
    @Autowired
    private MemberClient memberClient;


    private CommentMapper commentMapper;

    @Autowired
    public void setCommentMapper(CommentMapper commentMapper) {
        this.commentMapper = commentMapper;
    }


    @Override
    public Page<Comment> queryList(PageRequestDto page, CommentQuery query) {
        page.checkParam();
        Page<Comment> pages = new Page<>(page.getPage(), page.getSize());
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();

        //todo 搜索条件,待完善
        if (query != null) {
            if (query.getIsAnonymous() != null) {
                wrapper.gt(Comment::getIsAnonymous, query.getIsAnonymous());
            }
            if (query.getGoodId() != null) {
                wrapper.eq(Comment::getGoodId, query.getGoodId());
            }
            if (query.getStartDateTime() != null && query.getEndDateTime() != null) {
                wrapper.between(Comment::getCreatedAt, query.getStartDateTime(), query.getEndDateTime());
            }
        }
        Page<Comment> commentPage = commentMapper.selectPage(pages, wrapper);
        commentPage.getRecords().forEach(item -> {
            if (item.getGoodId() != null) {
                ResponseResult<Good> byId = goodClient.getDetailById(item.getGoodId());
                item.setGood(byId.getData());
            }

            if (item.getMemberId() != null) {
                ResponseResult<Member> byId = memberClient.getById(item.getMemberId());
                item.setMember(byId.getData());
            }
        });
        return commentPage;
    }

    @Override
    public boolean like(Integer id) {
        Comment byId = this.getById(id);
        try {
            byId.setUpdatedAt(LocalDateTime.now());
            byId.setLikeCount(byId.getLikeCount() + 1);
        } catch (Exception e) {
            throw new RuntimeException("服务器异常");
        }
        return this.updateById(byId);
    }




    /**
     * 评论的树形结构查询
     * @param comment
     * @return
     */

    @Override
    public List<Comment> findAll(Comment comment) {
        return commentMapper.findAll(comment);
    }

    @Cacheable(key = "'all'")
    @Override
    public List<Comment> findAll() {
        return commentMapper.selectList(null);
    }

    @Cacheable(key = "'tree'")
    @Override
    public List<Comment> findTree() {
        List<Comment> comments = proxy().findAll();
        return buildCommentTree(comments);
    }

    @Cacheable(key = "#goodId + '_tree'")
    @Override
    public List<Comment> findTreeByGoodId(Integer goodId) {
        Comment query = new Comment();
        query.setGoodId(goodId);
        List<Comment> comments = commentMapper.findAll(query);
        return buildCommentTree(comments);
    }

    @Cacheable(key = "#id")
    @Override
    public Comment findById(Integer id) {
        List<Comment> allComments = proxy().findAll();
        Map<Integer, Comment> commentMap = allComments.stream()
                .collect(Collectors.toMap(Comment::getId, c -> c));

        return commentMap.get(id);
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean save(Comment comment) {
        return this.commentMapper.insert(comment) == 1;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(Comment comment) {
        return this.commentMapper.updateById(comment) == 1;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int deleteById(Integer id) {
        Comment comment = proxy().findById(id);
        if (comment == null) {
            return 0;
        }
        return this.commentMapper.deleteById(id);
    }

    /**
     * 构建评论树形结构
     * 1. 主评论（parentId=0）作为根节点
     * 2. 回复评论作为子节点
     * 3. 追评作为子节点
     */
    private List<Comment> buildCommentTree(List<Comment> comments) {
        // 按ID索引所有评论，便于快速查找
        Map<Integer, Comment> commentMap = comments.stream()
                .collect(Collectors.toMap(Comment::getId, c -> c));

        // 初始化所有评论的关联列表
        for (Comment comment : comments) {
            if (comment.getAdditionalReviews() == null) {
                comment.setAdditionalReviews(new ArrayList<>());
            }
            if (comment.getReplies() == null) {
                comment.setReplies(new ArrayList<>());
            }
        }

        List<Comment> rootComments = new ArrayList<>();

        for (Comment comment : comments) {
            if (comment.getParentId() == 0) {
                // 顶级评论
                rootComments.add(comment);
            } else {
                // 处理子评论
                Comment parent = commentMap.get(comment.getParentId());
                if (parent != null) {
                    if (Boolean.TRUE.equals(comment.getIsAdditional())) {
                        // 追评
                        parent.getAdditionalReviews().add(comment);
                    } else {
                        // 普通回复
                        parent.getReplies().add(comment);
                    }
                }
            }
        }

        return rootComments;
    }

    /**
     * 获取当前类的代理实现
     */
    private CommentService proxy() {
        return (CommentService) AopContext.currentProxy();
    }
}

